<!-- 产品创建类型 -->
<template>
  <el-dialog
    class="dialogAdapter"
    :destroy-on-close="true"
    @close="handleClose"
    style="border-radius: 10px"
    v-model="props.visible"
    :title="`${!type ? '创建' : '编辑'}产品`"
  >
    <!--产品from -->
    <el-form ref="ruleFormRef" :model="d.form" label-position="top">
      <!-- @vue-ignore -->
      <el-upload
        class="avatar-uploader"
        action="#"
        :before-upload="beforeAvatarUpload"
        :http-request="handleRequestUpload"
        accept="image/jpg, image/jpeg, image/png"
        :show-file-list="false"
      >
        <img v-if="d.form.cover && isShowAvatar" :src="d.form.cover" class="cover-img" />
        <img v-if="d.form.cover && isShowAvatar" :src="EditAvatarSvg" alt="" class="edit-svg" />
        <el-icon v-else class="avatar-uploader-icon">
          <Plus />
        </el-icon>
      </el-upload>
      <el-form-item prop="name" label="名称" :rules="[{ required: true, message: '请输入名称' }]">
        <el-input v-model="d.form.name" autocomplete="off" placeholder="请输入名称" />
      </el-form-item>
      <el-form-item prop="price" label="价格" :rules="[{ required: true, message: '请输入价格' }]">
        <el-input v-model.number="d.form.price" autocomplete="off" placeholder="请输入价格" />
      </el-form-item>
      <el-form-item prop="inventory" label="库存" :rules="[{ required: true, message: '请输入库存' }]">
        <el-input v-model="d.form.inventory" autocomplete="off" placeholder="请输入库存" />
      </el-form-item>
      <el-form-item prop="specification" label="规格" :rules="[{ required: true, message: '请输入库存' }]">
        <el-input v-model="d.form.specification" autocomplete="off" placeholder="请输入规格" />
      </el-form-item>
      <el-form-item prop="info" label="详情">
        <el-input v-model="d.form.info" type="textarea" placeholder="请输入详情" />
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button v-if="!type" type="danger" @click="submitForm(ruleFormRef)"> 创建 </el-button>
        <el-button v-else type="danger" @click="submitEditForm(ruleFormRef)"> 编辑 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { APIVoiceAdd, APIVoiceUp } from "@/api/ApiSpeechModel"
import { ElMessage, FormInstance, UploadProps } from "element-plus"
import { onMounted, reactive, ref } from "vue"
// @ts-ignore
import debounce from "@/utils/debounce"
import pubsub from "pubsub-js"
import EditAvatarSvg from "@/assets/drawing/edit.svg"
import { apiProductAdd, apiProductUpdate } from "@/api/apiProduct"

interface Props {
  editData?: any
  type?: string
  visible: boolean
}

const emits = defineEmits(["editDpData", "close"])
const props = defineProps<Props>()
const ruleFormRef = ref()
const isShowAvatar = ref<boolean>(Boolean(props.editData && props.editData.isShowAvatar) as any)
const avatarImgFile = ref<any>(null)

// 上传头像之前
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  const image = new Image()
  const reader = new FileReader()

  return new Promise((resolve, reject) => {
    reader.onload = (e) => {
      if (typeof reader.result === "string") {
        image.src = reader.result
        image.onload = () => {
          const width = image.width
          const height = image.height
          if (width !== height) {
            ElMessage.error("头像图片必须为(1:1比例)")
            reject()
          } else {
            resolve()
          }
        }
      } else {
        reject()
      }
    }

    reader.readAsDataURL(rawFile)
  })
}

// 上传头像
const handleRequestUpload = debounce((file: any) => {
  if (file) {
    const allowedFormats = ["image/jpeg", "image/jpg", "image/png"]
    if (!allowedFormats.includes(file.file?.type)) {
      ElMessage({
        type: "error",
        message: "格式错误，只能上传 jpeg / jpg / png 图片格式"
      })
      return
    }

    const URL = window.URL || window.webkitURL
    avatarImgFile.value = file.file
    const imgSrc = URL.createObjectURL(file.file)
    isShowAvatar.value = true
    d.form.cover = imgSrc
  }
}, 300)

// 云模型from
const d = reactive({
  form: {
    name: "",
    price: "",
    inventory: "",
    info: "",
    specification: "",
    cover: ""
  }
})

// 清空数据
const dfData = {
  name: "",
  price: "",
  inventory: "",
  info: "",
  specification: "",
  cover: ""
}

onMounted(() => {
  console.log("props.editData", props.editData)
  if (props.editData && props.type) {
    d.form = props.editData
  }
})

// 创建提交
const submitForm = debounce((formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      console.log({ ...d.form, cover: avatarImgFile.value })

      let { code } = await apiProductAdd({ ...d.form, cover: avatarImgFile.value })
      if (code === 200) {
        pubsub.publish("UPDAPRODUCTLIST")
        handleClose()
        ElMessage({
          type: "success",
          message: "创建成功"
        })
        d.form = dfData
      }
    } else {
      console.log("error submit!")

      return false
    }
  })
}, 300)

const handleClose = () => {
  emits("close")
}
// 编辑提交
const submitEditForm = debounce((formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      console.log(valid, d.form, "submit!")
      let { code, data } = await apiProductUpdate({ ...d.form, cover: avatarImgFile.value, id: props.editData.id })
      if (code === 200) {
        emits("editDpData", { ...d.form, ...data })
      }
    } else {
      console.log("error submit!")
      return false
    }
  })
}, 300)
</script>
<style lang="scss" scoped>
.avatar-uploader {
  position: relative;
  text-align: center;
  margin-bottom: 20px;

  .cover-img {
    width: 80px;
    height: 80px;
    border-radius: 20px;
  }

  .edit-svg {
    position: absolute;
    right: 0;
    bottom: 0;
    width: 32px;
    height: 32px;
    border-radius: 20px 0px;
    opacity: 0.8;
  }
}

::v-deep .avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 20px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  text-align: center;
}
</style>
